package com.mmc.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.mmc.common.result.Result;
import com.mmc.entity.Department;
import com.mmc.service.DepartmentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * 部门控制器
 *
 * @author kunfe
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/api/departments")
@RequiredArgsConstructor
@SaCheckLogin
@Tag(name = "部门管理", description = "部门管理相关接口")
public class DepartmentController {

    private final DepartmentService departmentService;

    @Operation(summary = "获取部门树")
    @GetMapping("/tree")
    public Result<List<Department>> getDeptTree() {
        List<Department> depts = departmentService.getDeptTree();
        return Result.ok(depts);
    }

    @Operation(summary = "获取所有启用的部门")
    @GetMapping("/enabled")
    public Result<List<Department>> getEnabledDepts() {
        List<Department> depts = departmentService.getEnabledDepts();
        return Result.ok(depts);
    }

    @Operation(summary = "获取所有部门列表")
    @GetMapping("/list")
    public Result<List<Department>> getDeptList(
            @RequestParam(required = false) String deptName,
            @RequestParam(required = false) Integer status) {
        
        List<Department> depts = departmentService.getAllDepts(deptName, status);
        return Result.ok(depts);
    }

    @Operation(summary = "根据父部门ID获取子部门")
    @GetMapping("/children/{parentId}")
    public Result<List<Department>> getDeptsByParentId(@PathVariable Long parentId) {
        List<Department> depts = departmentService.getDeptsByParentId(parentId);
        return Result.ok(depts);
    }

    @Operation(summary = "获取部门详情")
    @GetMapping("/{id}")
    public Result<Department> getDeptById(@PathVariable Long id) {
        Department dept = departmentService.getById(id);
        return Result.ok(dept);
    }

    @Operation(summary = "新增部门")
    @PostMapping
    public Result<Void> createDept(@Valid @RequestBody CreateDeptRequest request) {
        Department dept = new Department();
        dept.setParentId(request.getParentId());
        dept.setDeptName(request.getDeptName());
        dept.setDeptCode(request.getDeptCode());
        dept.setLeader(request.getLeader());
        dept.setPhone(request.getPhone());
        dept.setEmail(request.getEmail());
        dept.setSort(request.getSort());
        dept.setStatus(request.getStatus());
        dept.setRemark(request.getRemark());
        
        boolean success = departmentService.createDept(dept);
        return success ? Result.ok() : Result.fail("新增失败");
    }

    @Operation(summary = "更新部门")
    @PutMapping("/{id}")
    public Result<Void> updateDept(@PathVariable Long id, @Valid @RequestBody UpdateDeptRequest request) {
        Department dept = new Department();
        dept.setId(id);
        dept.setParentId(request.getParentId());
        dept.setDeptName(request.getDeptName());
        dept.setDeptCode(request.getDeptCode());
        dept.setLeader(request.getLeader());
        dept.setPhone(request.getPhone());
        dept.setEmail(request.getEmail());
        dept.setSort(request.getSort());
        dept.setStatus(request.getStatus());
        dept.setRemark(request.getRemark());
        
        boolean success = departmentService.updateDept(dept);
        return success ? Result.ok() : Result.fail("更新失败");
    }

    @Operation(summary = "删除部门")
    @DeleteMapping("/{id}")
    public Result<Void> deleteDept(@PathVariable Long id) {
        boolean success = departmentService.deleteDept(id);
        return success ? Result.ok() : Result.fail("删除失败");
    }

    @Operation(summary = "批量删除部门")
    @DeleteMapping("/batch")
    public Result<Void> batchDeleteDept(@Valid @RequestBody BatchDeleteRequest request) {
        boolean success = departmentService.batchDeleteDept(request.getIds());
        return success ? Result.ok() : Result.fail("删除失败");
    }

    @Operation(summary = "启用/禁用部门")
    @PutMapping("/{id}/status")
    public Result<Void> changeStatus(@PathVariable Long id, @RequestBody ChangeStatusRequest request) {
        boolean success = departmentService.changeStatus(id, request.getStatus());
        return success ? Result.ok() : Result.fail("操作失败");
    }

    @Operation(summary = "检查部门编码是否存在")
    @GetMapping("/check-code")
    public Result<Boolean> checkDeptCode(
            @RequestParam String deptCode,
            @RequestParam(required = false) Long excludeId) {
        boolean exists = departmentService.existsDeptCode(deptCode, excludeId);
        return Result.ok(exists);
    }

    @Operation(summary = "检查部门是否有子部门")
    @GetMapping("/{id}/has-children")
    public Result<Boolean> hasChildren(@PathVariable Long id) {
        boolean hasChildren = departmentService.hasChildren(id);
        return Result.ok(hasChildren);
    }

    @Operation(summary = "检查部门是否有用户")
    @GetMapping("/{id}/has-users")
    public Result<Boolean> hasUsers(@PathVariable Long id) {
        boolean hasUsers = departmentService.hasUsers(id);
        return Result.ok(hasUsers);
    }

    // DTO类
    @Data
    public static class CreateDeptRequest {
        private Long parentId = 0L;
        
        @NotBlank(message = "部门名称不能为空")
        private String deptName;
        
        private String deptCode;
        private String leader;
        private String phone;
        private String email;
        private Integer sort = 0;
        private Integer status = 1;
        private String remark;
    }

    @Data
    public static class UpdateDeptRequest {
        private Long parentId;
        
        @NotBlank(message = "部门名称不能为空")
        private String deptName;
        
        private String deptCode;
        private String leader;
        private String phone;
        private String email;
        private Integer sort;
        private Integer status;
        private String remark;
    }

    @Data
    public static class BatchDeleteRequest {
        @NotEmpty(message = "删除ID列表不能为空")
        private List<Long> ids;
    }

    @Data
    public static class ChangeStatusRequest {
        @NotNull(message = "状态不能为空")
        private Integer status;
    }
} 